package org.onion.pattern.kit.administdivision;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.*;

@Slf4j
public final class Areas {

    static final Map<String, String> codeAndName = new HashMap<>();
    static final Map<String, Set<String>> cityCodeAndCodeSet = new HashMap<>();

    static {
        InputStream resourceAsStream = Areas.class.getResourceAsStream("/administrative-divisions/areas.json");
        byte[] bytes = IoUtil.readBytes(resourceAsStream);
        JSONArray jsonArray = JSONUtil.parseArray(bytes);
        for (Object node : jsonArray) {
            JSONObject object = (JSONObject) node;
            String name = object.getStr("name");
            String code = object.getStr("code");
            String cityCode = object.getStr("cityCode") + "00";
            codeAndName.put(code, name);
            Set<String> cityCodeSet = cityCodeAndCodeSet.computeIfAbsent(cityCode, k -> new HashSet<>());
            cityCodeSet.add(code);
        }
    }

    public static Optional<String> findNameByCode(String code) {
        String name = codeAndName.get(code.trim());
        return Optional.ofNullable(name);
    }

    public static Set<String> findCodeByCityCode(String cityCode) {
        return cityCodeAndCodeSet.getOrDefault(cityCode, Collections.emptySet());
    }

//    public static Optional<String> findCodeByName(String name) {
//        String code = nameAndCode.get(name.trim());
//        return Optional.ofNullable(code);
//    }

}
